package fr.hoteia.appengine.archetype.server.web.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import fr.hoteia.appengine.archetype.client.Constants;

public class ServerUtil {

	/**
	 *
	 */
	public static String getHost(HttpServletRequest request) {
		return (String) request.getHeader(Constants.HOST);
	}

	/**
	 *
	 */
	public static String getReferer(HttpServletRequest request) {
		return (String) request.getHeader(Constants.REFERER);
	}

	/**
	 *
	 */
	public static boolean isLocalHostMode(HttpServletRequest request) {
		if (StringUtils.isNotEmpty(getHost(request)) && getHost(request).equalsIgnoreCase("localhost:")) {
			return true;
		}
		return false;
	}

	/**
	 *
	 */
	public static String getGeneratedKeyName() {
		String uuid = java.util.UUID.randomUUID().toString();
		uuid = uuid.replace(Constants.DASH, Constants.EMPTY);
		return uuid;
	}
	
	/**
	 *
	 */
	public static String getUserEmailEncodeAsUTF8(String email) {
		String userEmail = email;
		String userEmailEncode = null;
		try {
			userEmailEncode = URLEncoder.encode(userEmail, Constants.UTF8);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return userEmailEncode;
	}
	
	/**
	 *
	 */
	public static String getGoogleApplicationName(String publisher, String appName, int appVersion) {
		appName = appName.replace(Constants.DASH, Constants.EMPTY);
		return (publisher.toLowerCase() + Constants.DASH + appName.toLowerCase() + Constants.DASH + new Integer(appVersion).toString());
	}
	
	/**
	 *
	 */
	public static void addHeaderToResponseForOAuthGoogle(HttpServletResponse response, String consumerKey, String callBackURL) {
		response.addHeader("Authorization:", "OAuth");
		response.addHeader("oauth_signature_method", Constants.GOOGLE_OAUTH_SIGNATURE_METHOD);
		response.addHeader("oauth_consumer_key", consumerKey);
		response.addHeader("oauth_callback", callBackURL);
		response.setContentType("application/x-www-form-urlencoded");
	}

}
